<template>
  <a-form
    ref="formRef"
    class="login-form-wrapper"
    layout="vertical"
    :model="form"
    :rules="rules"
  >
    <div class="login-form-title">欢迎登录</div>
    <a-tabs v-model:active-key="tabActiveKey" size="mini" animation>
      <a-tab-pane key="1" title="账号登录" destroy-on-hide>
        <a-form-item field="account" validate-trigger="blur" hide-label>
          <a-input
            v-model="form.account"
            autocomplete="account"
            placeholder="账号"
          >
            <template #prefix>
              <icon-user />
            </template>
          </a-input>
        </a-form-item>
        <a-form-item field="password" validate-trigger="blur" hide-label>
          <a-input-password
            v-model="form.password"
            autocomplete="current-password"
            placeholder="请输入密码"
            allow-clear
          >
            <template #prefix>
              <icon-lock />
            </template>
          </a-input-password>
        </a-form-item>
        <a-checkbox
          checked="rememberPassword"
          :model-value="loginConfig.rememberPassword"
          @change="setRememberPassword"
        >
          记住密码
        </a-checkbox>
      </a-tab-pane>
    </a-tabs>
    <a-button
      type="primary"
      style="margin: 32px 0 6px"
      long
      :loading="loading"
      @click="handleSubmit"
    >
      登录
    </a-button>
    <a-button type="text" long class="login-form-register-btn" href="/register">
      注册
    </a-button>
  </a-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useStorage } from '@vueuse/core';
import { useUserStore } from '@/store';
import useLoading from '@/hooks/useLoading';
import { pick } from 'lodash';
import { Message } from '@arco-design/web-vue';
import {
  getUserByIdUsingGet,
  userLoginUsingPost
} from '@/service/backend/userController';
import { clearToken, setToken } from '@/utils/auth.ts';

const router = useRouter();
const userStore = useUserStore();
const formRef = ref();
const tabActiveKey = ref('1');
const { loading, setLoading } = useLoading();

const loginConfig = useStorage('login-config', {
  rememberPassword: true,
  account: 'admin', // 演示默认值
  password: 'admin123' // 演示密码
});
const form = reactive({
  account: loginConfig.value.account,
  password: loginConfig.value.password
});

const rules = {
  account: [{ required: true, message: '请输入正确账号' }],
  password: [
    { required: true, message: '请输入密码' },
    { minLength: 8, message: '密码至少8位' }
  ]
};

const handleSubmit = () => {
  if (loading.value) return;

  formRef.value.validateField(['account', 'password']).then(async res => {
    if (res) return;
    setLoading(true);
    try {
      const userInfoForm = pick(form, ['account', 'password']);

      const res = await userLoginUsingPost({ ...userInfoForm });
      if (res.code !== 0) {
        throw new Error(res.message);
      }
      //保存用户信息
      await userStore.fetchLoginUser();

      //使用cookie会话保存用户信息,用id代替token作为唯一标识
      setToken(res.data.id);

      const { redirect, ...othersQuery } = router.currentRoute.value.query;
      router.push({
        name: (redirect as string) || 'Dashboard',
        query: {
          ...othersQuery
        }
      });
      Message.success('登录成功');
      const { rememberPassword } = loginConfig.value;
      const { account, password } = userInfoForm;
      // 实际生产环境需要进行加密存储。
      loginConfig.value.account = rememberPassword ? account : '';
      loginConfig.value.password = rememberPassword ? password : '';
    } catch (error) {
      Message.error('登录失败,' + error.message);
      clearToken();
    } finally {
      setLoading(false);
    }
  });
};

const setRememberPassword = (value: boolean) => {
  loginConfig.value.rememberPassword = value;
};
</script>

<style lang="less" scoped>
.login-form {
  &-wrapper {
    width: 330px;
    padding: 24px 24px 12px;
    overflow: hidden;
    background-color: var(--color-bg-1);
    border: 1px solid var(--color-border-2);
    border-radius: var(--border-radius-large);
  }

  &-title {
    margin-bottom: 16px;
    font-size: 24px;
    font-weight: 500;
    line-height: 32px;
    color: var(--color-text-1);
  }

  &-actions {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    margin-top: 24px;
    margin-bottom: 6px;
  }

  &-register-btn {
    color: var(--color-text-3) !important;
  }

  &-more {
    justify-content: center;

    .arco-icon {
      font-size: 20px;
      cursor: pointer;
      transition: transform 0.2s ease;

      &:hover {
        transform: scale(1.3);
      }
    }
  }
}

:deep(.arco-tabs-content) {
  height: 155px;
}
</style>
